package com.common.groovy.action;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.common.dao.LowCodeDao;
import com.common.groovy.helper.GroovyHelper;
import com.common.groovy.model.ActionModel;
import com.common.groovy.model.DataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Description:
 * @Date: 2025/7/11 09:46
 */
@Component("SimpleRealDelete")
public class SimpleRealDeleteAction implements IAction<JSONObject, JSONObject> {

    @Autowired
    private GroovyHelper groovyHelper;

    @Autowired
    private LowCodeDao lowCodeDao;

    @Override
    public JSONObject execute(ActionModel actionDetail, DataModel data, JSONObject params) {
        JSONObject result = JSONUtil.createObj();
        String beforeShell = actionDetail.getBefore();
        String sql = actionDetail.getDetail().getSaveScript();
        String afterShell = actionDetail.getAfter();
        if (StringUtils.hasText(beforeShell)) {
            groovyHelper.execute(beforeShell, params);
        }
        if (StringUtils.hasText(sql)) {
            result = executeSql(sql, params);
        }
        if (StringUtils.hasText(afterShell)) {
            JSONObject afterParams = JSONUtil.createObj();
            afterParams.set("request", params);
            afterParams.set("response", result);
            groovyHelper.execute(afterShell, afterParams);
        }
        return result;
    }

    @Override
    public JSONObject processSql(String sql) {
        Integer rows = lowCodeDao.simpleDeleteExecute(sql);
        JSONObject result = JSONUtil.createObj();
        result.set("rows", rows);
        return result;
    }
}
